<template>
  <nav class="toc" aria-label="文档目录">
    <div class="toc__header">目录</div>
    <div v-if="!nodes?.length" class="toc__empty">暂无标题</div>
    <ul v-else class="toc__list">
      <TocNodeItem
        v-for="n in nodes"
        :key="n.id"
        :node="n"
        :active-id="activeId || undefined"
        @navigate="$emit('navigate', $event)"
        @insertCardUnder="$emit('insertCardUnder', $event)"
      />
    </ul>
  </nav>
</template>

<script lang="ts" setup>
import TocNodeItem from './TocNodeItem.vue'

export interface TocCounts { cards: number; images: number; links: number }
export interface TocNode { id: string; level: 1 | 2 | 3; text: string; children: TocNode[]; counts: TocCounts }

defineProps<{ nodes: TocNode[]; activeId?: string | null }>()
defineEmits<{ (e: 'navigate', id: string): void; (e: 'insertCardUnder', id: string): void }>()
</script>

<style scoped>
.toc {
  background: #fff;
  /* border: 1px solid #f0f2f5; */
  border-radius: 10px;
  padding: 8px;
}
.toc__header {
  font-weight: 700;
  font-size: 14px;
  padding: 8px 8px 4px 8px;
}
.toc__empty {
  color: #9aa4af;
  padding: 8px;
}
.toc__list {
  list-style: none;
  margin: 0;
  padding: 6px;
}
.toc-item {
  margin: 2px 0;
}
.toc-item__row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  padding: 6px 8px;
  border-radius: 8px;
  cursor: pointer;
}
.toc-item__row:hover {
  background: #f5f7fa;
}
.toc-item.active > .toc-item__row {
  background: #eaf3fe;
  border-left: 3px solid #3d99f5;
}
.toc-item__text {
  display: inline-block;
  max-width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.toc-badge {
  font-size: 12px;
  color: #60758a;
  margin-left: 6px;
}
.toc-insert {
  margin-left: 6px;
  border: none;
  background: #eaf3fe;
  color: #3d99f5;
  border-radius: 6px;
  padding: 2px 6px;
  cursor: pointer;
}
.toc-insert:hover { background: #d7e9fe; }

/* Indentation by level */
.level-1 > .toc-item__row { padding-left: 8px; }
.level-2 > .toc-item__row { padding-left: 20px; }
.level-3 > .toc-item__row { padding-left: 32px; }
</style>
